package com.sky.aspect;

import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import com.sky.entity.OperateLog;
import com.sky.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.sky.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Long operateUser = BaseContext.getCurrentId();
        LocalDateTime operateTime = LocalDateTime.now();
        String className = joinPoint.getTarget().getClass().getName();

        String methodName = joinPoint.getSignature().getName();

        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed();//方法的返回值

        long end = System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);
        Long costTime = end -start;

        //插入OperateLog对象数据
        OperateLog operateLog=new OperateLog(null,operateUser,operateTime,className,methodName,methodParams,returnValue,costTime) ;

        operateLogMapper.insert(operateLog);
        log.info("日志:{}",operateLog);
        return result;
    }
}
